# questionnaire/views.py
from django.shortcuts import render, redirect
from .models import QuestionQ1, QuestionQ2, QuestionQ3, QuestionQ4, QuestionQ5, UserAnswer
import random
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist  # Add this import
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from apps.contents.utils import analyze_questionnaire_results # 导入AI分析函数
from django.shortcuts import redirect, render # 确保导入 redirect 和 render
from django.urls import reverse # 用于反向解析 URL
import markdown
from django.utils.safestring import mark_safe

def start_test(request):
    print(f"--- Session in start_test: {dict(request.session.items())}") # 调试打印
    q1_questions = QuestionQ1.objects.all()
    q2_questions = QuestionQ2.objects.all()
    q3_questions = QuestionQ3.objects.all()
    q4_questions = QuestionQ4.objects.all()
    q5_questions = QuestionQ5.objects.all()

    context = {
        'q1_questions': q1_questions,
        'q2_questions': q2_questions,
        'q3_questions': q3_questions,
        'q4_questions': q4_questions,
        'q5_questions': q5_questions,
    }
    return render(request, '2.html', context)

def question_test(request, question_type):
    if question_type == 'q1':
        question_model = QuestionQ1
    elif question_type == 'q2':
        question_model = QuestionQ2
    elif question_type == 'q3':
        question_model = QuestionQ3
    elif question_type == 'q4':
        question_model = QuestionQ4
    elif question_type == 'q5':
        question_model = QuestionQ5
    else:
        return render(request, 'error.html', {'error_message': '无效的题型'})

    all_questions = list(question_model.objects.all())
    if len(all_questions) >= 5:
        random_questions = random.sample(all_questions, 5)
    else:
        random_questions = all_questions

    context = {
        'questions': random_questions,
        'question_type': question_type
    }
    return render(request, '1.html', context)

@login_required
def submit_test(request):
    if request.method == 'POST':
        # 获取问题类型
        question_type = request.POST.get('question_type')
        
        # 初始化计数器
        correct_count = 0
        total_questions = 0
        
        # 遍历所有提交的答案
        for key, value in request.POST.items():
            # 检查键是否以 'question_' 开头且不是 'question_type'
            if key.startswith('question_') and key != 'question_type':
                try:
                    # 尝试提取问题ID
                    question_id = int(key.split('_')[1])
                    
                    # 获取正确答案
                    if question_type == 'q1':
                        question = QuestionQ1.objects.get(id=question_id)
                    elif question_type == 'q2':
                        question = QuestionQ2.objects.get(id=question_id)
                    elif question_type == 'q3':
                        question = QuestionQ3.objects.get(id=question_id)
                    elif question_type == 'q4':
                        question = QuestionQ4.objects.get(id=question_id)
                    elif question_type == 'q5':
                        question = QuestionQ5.objects.get(id=question_id)
                    else:
                        return render(request, 'error.html', {'error_message': '无效的题型'})
                    
                    # 检查答案是否正确
                    if value == question.answer:
                        correct_count += 1
                    
                    total_questions += 1
                except (ValueError, IndexError):
                    # 跳过无法解析的键
                    continue
                except ObjectDoesNotExist:
                    # 跳过找不到的问题
                    continue
        
        # 将结果存入数据库，如果已存在则更新
        from .models import UserTestResult
        user = request.user
        
        # 使用 update_or_create 方法更新或创建记录
        UserTestResult.objects.update_or_create(
            user=user,
            question_type=question_type,
            defaults={
                'correct_count': correct_count,
                'total_count': total_questions
            }
        )
        
        print(f"--- 已将 {question_type} 的测试结果保存到数据库")

        # 重定向
        return redirect('questionnaire:start_test')

    # 如果不是POST请求，重定向到开始页面
    return redirect('questionnaire:start_test')

# 修改 get_all_results 函数
@login_required
def get_all_results(request):
    # 定义题型代码到中文名称的映射
    type_mapping = {
        'q1': '常识题',
        'q2': '判断推理',
        'q3': '数量关系',
        'q4': '言语理解与表达',
        'q5': '资料分析'
    }

    # 从数据库中获取所有测试结果
    from .models import UserTestResult
    user = request.user
    user_results = UserTestResult.objects.filter(user=user)
    
    # 检查是否有结果，如果没有则重定向
    if not user_results.exists():
        # 可以添加一个消息提示用户需要先完成测试
        return redirect('questionnaire:start_test')

    # 转换结果为字典格式
    all_results_raw = {}
    for result in user_results:
        all_results_raw[result.question_type] = {
            'correct_count': result.correct_count,
            'total_count': result.total_count,
            'question_type': result.question_type
        }

    # 转换结果字典的键为中文名称
    all_results_mapped = {}
    for q_type, result_data in all_results_raw.items():
        chinese_name = type_mapping.get(q_type)
        if chinese_name:
            all_results_mapped[chinese_name] = result_data

    # 调用 AI 分析函数处理 all_results_mapped
    try:
        # 获取用户名
        username = request.user.username
        # 将转换后的字典传递给 AI 分析函数
        questionnaire_analysis = analyze_questionnaire_results(username, all_results_mapped)
        # 将 AI 分析结果存储在 session 中，方便后续页面使用
        request.session['questionnaire_analysis'] = questionnaire_analysis
        # 也存储原始结果用于绘图
        request.session['questionnaire_raw_results'] = all_results_mapped
    except Exception as e:
        # 处理调用 AI 分析时可能发生的错误
        print(f"Error during questionnaire analysis: {e}")
        request.session['questionnaire_analysis'] = "问卷分析失败，请稍后重试。"

    # 重定向到用户中心或完善信息页面
    return redirect(reverse('contents:careerhub'))

# 修改 clear_results 函数，使其清除数据库中的记录
@require_POST
@login_required
def clear_results(request):
    """清除所有测试结果"""
    from .models import UserTestResult
    user = request.user
    
    # 删除该用户的所有测试结果
    UserTestResult.objects.filter(user=user).delete()
    
    # 同时清除session中的相关数据
    if 'questionnaire_analysis' in request.session:
        del request.session['questionnaire_analysis']
    if 'questionnaire_raw_results' in request.session:
        del request.session['questionnaire_raw_results']
    
    return JsonResponse({'status': 'success'})

# 修改 check_completed 函数，使其检查数据库而不是session
def check_completed(request, question_type):
    """检查指定题型是否已完成"""
    if not request.user.is_authenticated:
        return JsonResponse({'completed': False})
        
    from .models import UserTestResult
    completed = UserTestResult.objects.filter(
        user=request.user, 
        question_type=question_type
    ).exists()
    
    return JsonResponse({'completed': completed})


def paper_view(request):
    # 获取问卷分析结果
    questionnaire_analysis = request.session.get('questionnaire_analysis', '')
    
    # 将markdown格式转换为HTML
    questionnaire_html = mark_safe(markdown.markdown(questionnaire_analysis))
    
    context = {
        'questionnaire': questionnaire_html,
    }
    
    return render(request, 'paper.html', context)